package com.zhiwang.planet.mvvm.viewmodel.main

import android.annotation.SuppressLint
import android.view.View
import android.widget.RadioGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import androidx.lifecycle.*
import com.zhiwang.planet.BR
import com.zhiwang.planet.R
import com.zhiwang.planet.mvvm.model.RestApi
import com.zhiwang.planet.mvvm.model.entity.main.*
import com.zhiwang.planet.ui.WebViewActivity
import com.zhiwang.planet.util.Toaster
import com.zhiwang.planet.util.androidSchedule
import com.zhiwang.planet.util.responseFunc
import io.reactivex.Observable.zip
import io.reactivex.functions.BiFunction
import me.tatarka.bindingcollectionadapter2.ItemBinding
import javax.inject.Inject

data class Zip(var notifications: NotificationBody, var messages: MessageBody)

interface SetReadCallBack {
    fun onCallBack()
}

class ConnectionProto(var type: String, var id: String, var cb: SetReadCallBack)

object ConnectionViewModel : ViewModel() {
    var message = MutableLiveData<ConnectionProto>()

    var linkEvent = MutableLiveData<String>()


    fun reset() {
        if (message.value is ConnectionProto)
            message = MutableLiveData()

        if (linkEvent.value?.isNotEmpty() != false) {
            linkEvent = MutableLiveData()
        }
    }
}



class MessageViewModel @Inject constructor(var context: AppCompatActivity, var restApi: RestApi, var lifeCycleOwner: Lifecycle) : ViewModel(), LifecycleOwner {


    override fun getLifecycle(): Lifecycle {
        return lifeCycleOwner
    }


    init {

        ConnectionViewModel.reset()

        ConnectionViewModel.linkEvent.observe(this, Observer {
            WebViewActivity.load(context, it)
        })

        ConnectionViewModel.message.observe(this, Observer {

            setRead(it.type, it.id, it.cb)
        })
    }


    val notificationBinding = ItemBinding.of<NotificationItemViewModel>(BR.notificationItemViewModel, R.layout.item_notification)

    val notifcations = MutableLiveData<List<NotificationItemViewModel>>()


    val messageBinding = ItemBinding.of<MessageItemViewModel>(BR.messageItemViewModel, R.layout.item_message)
    val messages = MutableLiveData<List<MessageItemViewModel>>()


    val notificationChecked = MutableLiveData<Boolean>(true)

    //通知rv是否显示
    val notificationVisibility = MutableLiveData<Int>(View.VISIBLE)

    //消息是否显示
    val msgVisibility = MutableLiveData<Int>(View.GONE)

    val emptyHintAlpha = MutableLiveData<Int>(0)

    val notificationDot = MutableLiveData(false)

    val msgDot = MutableLiveData<Boolean>(false)

    fun onCheckedChange(v: RadioGroup, id: Int) {
        when (id) {
            R.id.rd_notification -> {
                notificationChecked.value = true
                emptyHintAlpha.value = if (notifcations.value?.isEmpty() == true) 255 else 0
                notificationVisibility.value = if (notifcations.value?.isEmpty() == true) View.GONE else View.VISIBLE
                msgVisibility.value = View.GONE
            }
            R.id.rd_msg -> {
                notificationChecked.value = false
                msgVisibility.value =
                        if (messages.value?.isEmpty() == true)
                            View.GONE
                        else View.VISIBLE
                notificationVisibility.value = View.GONE
                emptyHintAlpha.value =
                        if (messages.value?.isEmpty() == true) 255 else 0

            }

        }
    }


    @SuppressLint("CheckResult")
    fun start() {

        zip(restApi.getNotifications(NotificationRequest.notification()).responseFunc(),
                restApi.getMessages(NotificationRequest.message()).responseFunc(),
                BiFunction<NotificationBody, MessageBody, Zip> { t1, t2 -> Zip(t1, t2) })
                .androidSchedule()
                .subscribe({
                    notifcations.value = mapNotificationModel(it.notifications.list)
                    messages.value = mapMessageModel(it.messages.list)
                    notificationVisibility.value =
                            if (it.notifications.list.isNotEmpty() && notificationChecked.value == true)
                                View.VISIBLE
                            else View.GONE
                    msgVisibility.value =
                            if (it.messages.list.isNotEmpty() && notificationChecked.value == false)
                                View.VISIBLE
                            else View.GONE

                    msgDot.value = it.messages.count > 0
                    notificationDot.value = it.notifications.count > 0
                }, {
                    it?.message?.apply { Toaster.message(this) }
                }, {

                })


    }

    @SuppressLint("CheckResult")
    fun setRead(type: String, id: String, cb: SetReadCallBack) {

        restApi.setMessageRead(SetReadRequest.create(type, id))
                .androidSchedule()
                .responseFunc()
                .subscribe({
                    cb.onCallBack()

                    if (type == "0")
                        notificationDot.value = it > 0
                    if (type == "1")
                        msgDot.value = it > 0

                }, {
                    it.message?.apply { Toaster.message(this) }
                }, {

                })

    }


    fun deleteRead() {
        if (notificationChecked.value == true) {
            deleteNotificationRead()
        } else deleteMessageRead()
    }

    @SuppressLint("CheckResult")
    fun deleteNotificationRead() {

        restApi.deleteNotificationRead(DeleteReadRequest.notification())
                .androidSchedule()
                .responseFunc()
                .subscribe({
                    notifcations.value = mapNotificationModel(it.list)
                    notificationDot.value = it.count > 0
                    Toaster.message("消息已删除")
                }, {
                    it.localizedMessage?.apply { Toaster.message(this) }
                }, {

                })
    }


    @SuppressLint("CheckResult")
    private fun deleteMessageRead() {

        restApi.deleteMessageRead(DeleteReadRequest.message())
                .androidSchedule()
                .responseFunc()
                .subscribe({
                    messages.value = mapMessageModel(it.list)
                    msgDot.value = it.count > 0
                }, {
                    it.localizedMessage?.apply { Toaster.message(this) }
                }, {

                })
    }

    private fun mapMessageModel(messages: List<Message>): List<MessageItemViewModel> {
        return messages.map { MessageItemViewModel(it.id, "1", it.content, ObservableField(it.isRead == 1), it.diamond, it.bean) }

    }

    private fun mapNotificationModel(it: List<Notification>): List<NotificationItemViewModel> {
        return it.map { NotificationItemViewModel(it.id, it.type, it.title, it.content, it.date, ObservableBoolean(it.hasRead == 1), it.link) }
    }

}